/*
 * $Id: HiveMindObjectProvider.java 6 2008-02-03 23:14:51Z mlusetti $
 * --------------------------------------------------------------------------------------
 * Copyright (c) Massimo Lusetti <mlusetti@gmail.com>.  All rights reserved.
 *
 * The software in this package is published under the terms of the BSD style
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */
package it.datacode.t5hivebridge.provider;

import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.Registry;
import org.apache.hivemind.impl.RegistryBuilder;
import org.apache.tapestry.ioc.AnnotationProvider;
import org.apache.tapestry.ioc.ObjectLocator;
import org.apache.tapestry.ioc.ObjectProvider;
import org.slf4j.Logger;

/**
 * HiveMind based {@link ObjectProvider} which will serve HiveMind
 * services through Tapestry5 IoC context.
 * 
 * @author Massimo Lusetti <mlusetti@gmail.com>
 *
 */
public class HiveMindObjectProvider implements ObjectProvider
{
    private final Logger _logger;
    
    private Registry _registry;
    
    
    public HiveMindObjectProvider(Logger logger)
    {
        _logger = logger;
//        initialise();
    }

    void initialise()
        {
            if (_registry == null)
            {
                _logger.debug("Initializing HiveMind registry with default builder");
                _registry = RegistryBuilder.constructDefaultRegistry();
            }
        }


    /**
     * At fist call initialize the HiveMimind {@link org.apache.hivemind.Registry} the try to get
     * the service by type (tClass)
     * @param tClass the service interface type to retreive from HiveMind
     * @param annotationProvider the {@link org.apache.tapestry.ioc.AnnotationProvider} (unused)
     * @param objectLocator the {@link org.apache.tapestry.ioc.ObjectLocator)
     * @return the proxy instance for the requested service or {@code null} in case.
     */
    public <T> T provide(Class<T> tClass, AnnotationProvider annotationProvider, ObjectLocator objectLocator)
    {
        initialise();

        if (_registry == null)
            throw new RuntimeException("HiveMind Registry not configured");

        try
        {
            Object service = _registry.getService(tClass);
            // NOTE: ClassCastException should be trapped by HiveMind registry method
            return tClass.cast(service);
        }
        catch (ApplicationRuntimeException are)
        {
            String msg = "Impossibile to locate the service " +
                         " for type " + tClass.getCanonicalName() +
                         " from HiveMind registry";
            _logger.warn(msg, are);
            return null;
        }
    }
}
